package com.infoauto.opc.gateway.messages.model;

import com.infoauto.opc.gateway.messages.handler.MqttListener;
import com.infoauto.opc.gateway.messages.handler.SimpleMqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;

//MQTT协议使用者
public abstract class MqttAccess {

    private String clientId;

    private MqttListener mqttListener;

    private MqttPahoClientFactory clientFactory;

    protected MqttClient mqttClient;

    public MqttAccess(MqttPahoClientFactory clientFactory, String clientId, MqttListener mqttListener) {
        this.clientId = clientId;
        this.mqttListener = mqttListener;
        this.clientFactory = clientFactory;
    }

    /**
     * 连接
     * @throws MqttException
     */
    public void connect() throws MqttException {
        if (isConnected()) {
            return;
        }
        MqttConnectOptions options = clientFactory.getConnectionOptions();
        String[] serverURIs = options.getServerURIs();
        mqttClient = (MqttClient) clientFactory.getClientInstance(serverURIs[0], clientId);
        if (mqttListener != null) {
            mqttClient.setCallback(new SimpleMqttCallback(mqttListener, mqttClient, this));
        }
        mqttClient.connect(options);
    }

    /**
     * 判断是否连接
     * @return
     */
    public boolean isConnected() {
        return mqttClient != null && mqttClient.isConnected();
    }

    /**
     * 取消连接
     * @throws MqttException
     */
    public void disconnect() throws MqttException {
        if (isConnected()) {
            mqttClient.disconnect();
        }
    }

    /**
     * 关闭连接
     * @throws MqttException
     */
    public void close() throws MqttException {
        if (mqttClient != null) {
            mqttClient.close();
        }
    }
}
